<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" >
				<el-form-item>
					<el-input v-model="keyword" placeholder="请输入关键字..."></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onsale">上架</el-button>
          <el-button type="primary" @click="offsale">下架</el-button>
        </el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pets" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="50">
			</el-table-column>
			<el-table-column prop="name" label="宠物名称" width="120">
			</el-table-column>
			<el-table-column prop="costprice" label="成本价" width="80">
			</el-table-column>
			<el-table-column prop="saleprice" label="售价" width="80" sortable>
			</el-table-column>
			<el-table-column prop="type.name" label="品种" width="70" >

			</el-table-column>
      <el-table-column prop="state" label="状态" width="100" >
        <template scope="aa">
          <span v-if="aa.row.state==1" style="color: #13ce66">上架</span>
          <span v-else style="color: red">下架</span>
        </template>
      </el-table-column>
      <el-table-column prop="onsaleTime" label="上架时间" width="100" >
      </el-table-column>
      <el-table-column prop="offsaleTime" label="下架时间" width="100" >
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="100" >
      </el-table-column>
      <el-table-column prop="user.username" label="领养用户" width="80" >
      </el-table-column>
      <el-table-column prop="shop.name" label="所属店铺" width="90" >
      </el-table-column>

			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleSave(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :current-page="currentPage"
                     :page-size="pageSize" :total="totals" style="float:right;">
      </el-pagination>
		</el-col>

		<!--编辑和添加的对话框-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false" width="80%">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <!-- prop="name" 需要验证就加上这个属性，不需要验证就不加 -->
				<el-form-item label="宠物名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="成本" prop="costprice">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售价" prop="saleprice">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="品种" prop="typeId">
          <el-cascader v-model="saveForm.typeId"
                       :options="petTypeTree"
                       :props="{
                checkStrictly: true,
                label: 'name',//级联框显示那个属性的值
                value: 'id'  //回显时需要，回传值时也需要
                 }"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="店铺" prop="shopId">
          <!--v-model双向绑定要回显的数据,v-for遍历这个模型数据; label=要回显的哪一个值;
          value=用来传值,将对象的id值传递给shopId;shopId是为了与v-for中每一个对象(item)对应，找到回显那个数据-->
          <el-select v-model="saveForm.shopId" placeholder="请选择">
            <el-option
                v-for="item in shops"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.tel }}</span>
            </el-option>
          </el-select>
        </el-form-item>

				<el-form-item label="启用状态" >
					<el-radio-group v-model="saveForm.state">
						<el-radio class="radio" :label="1">上架</el-radio>
						<el-radio class="radio" :label="0">下架</el-radio>
					</el-radio-group>
				</el-form-item>

      <el-form-item label="资源" prop="resources">
        <el-upload class="upload-demo"
                   action="http://localhost:8080/fastDfs"
                   :on-remove="handleRemove"
                   :on-success="handleSuccess"
                   :file-list="fileList"
                   list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="简介" prop="intro">
        <!-- v-if="saveForm.petDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
        <quill-editor v-model="saveForm.petDetail.intro"
        v-if="saveForm.petDetail" :options="quillOption">
        </quill-editor>
      </el-form-item>
      <el-form-item label="领养须知" prop="orderNotice" >
        <quill-editor v-model="saveForm.petDetail.adoptNotice"
                      v-if="saveForm.petDetail" :options="quillOption">
        </quill-editor>
      </el-form-item>
      </el-form>

			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getPetListPage, removePet, batchRemovePet, savePet, addPet } from '../../api/api';
  //引入Vue的ueditor的资源

  import { quillEditor } from "vue-quill-editor"; //调用编辑器
  import 'quill/dist/quill.core.css';
  import 'quill/dist/quill.snow.css';
  import 'quill/dist/quill.bubble.css';
  import quillConfig from '../../common/js/quill-config';
	export default {
    components: {
      quillEditor
    },
		data() {
			return {
        fileList:[],
        quillOption: quillConfig,
        //级联框模型数据
        petTypeTree: [],
			  keyword: '',
			  //模型数据
        pets: [],
        users: [],
        shops: [],
        types: [],
				totals: 0,
				currentPage: 1,
        pageSize:5,
				listLoading: false,//加载框
        //级联框模型数据

				sels: [],//列表选中列

        //1.添加和修改的相关数据
        title: '',

				saveFormVisible: false,//控制对话框是否显示 - 默认不显示
				saveLoading: false,    //加载框
				saveFormRules: {
					name: [
						{ required: true, message: '请输入名称', trigger: 'blur' }
					],
				},


				//2.添加和编辑对话框 数据
				saveForm: {
					id: null,
          name:'',
          costprice: null,
          saleprice: null,
          typeId: null,
          shopId: null,
          userId: null,
          state: 1,
          resources: '',
          petDetail:{
            intro: '',
            adoptNotice: '',
          }
				},

				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//新增界面数据
				addForm: {
          id: null,
          name:'',
          costprice: null,
          saleprice: null,
          typeId: null,
          shopId: null,
          userId: null,
          state: 0,
          petDetail:{
            intro: '',
            adoptNotice: '',
          }
				}

			}
		},
		methods: {
      getShops(){
        this.$http.get("/shop").then((res) =>{
          //将所有的员工赋值给shops
          this.shops = res.data;
        })
      },
      //9.获取所有的经理
      getUsers(){
        this.$http.get("/user").then((res) =>{
          //将所有的员工赋值给users
          this.users = res.data;
        })
      },
      //1.批量删除按钮，选项改变的时候就会触发
    selsChange: function (sels) {
      this.sels = sels;
    },
    //2.批量删除
    batchRemove: function () {
      //获取数组中每一个对象的id，- 数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;//显示列表的加载框
        this.$http.patch("/pet/",ids).then(res =>{
          this.listLoading = false;
          if(res.data.success){
            this.$message("删除成功")
            this.getPets();
          }else{
            this.$message.error("网络异常，请稍后重试【500】");
          }
        }).catch((res) =>{
          this.$message.error("网络异常，请稍后重试【服务器没开，404,400】")
        })
      }).catch(()=>{
      })
    },

      //3.删除
      handleDel: function (index, row) {
        this.$confirm("确认删除该记录吗？","提示",{
          type: 'warning'
        }).then(() =>{
          this.listLoading =true;
          this.$http.delete("/pet/"+row.id).then(res => {
                this.listLoading = false;
                if(res.data.success){
                  this.$message.success("删除成功");
                  //删除优化:计算总页数
                  var totalPage=Math.ceil(this.totals/this.pageSize);
                  //删除最后一页的最后一条数据，而且不能是第一页的时候，让当前页=当前页-1
                  if(
                      this.currentPage==totalPage &&(this.totals-1)%this.pageSize==0&& this.currentPage!=1
                  ){
                    this.currentPage =this.currentPage-1;
                    this.getPets();
                  }
                }else{
                  this.$message.error("网络异常，请稍后重试【500】")
                }
            }).catch( res=>{
              this.message.error("网络异常，请稍后重试[服务器没开，404,400]")
          })
        }).catch(() => {
        })
      },
		  //4.高级查询
		  keywordQuery(){
        //防止高级查询时查询出为空的现象【当前是第5页，但是高级查询的结果没有5页】
        this.currentPage=1;
        this.getPets();
      },
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getPets();
			},
			//5.获取用户列表
			getPets() {
			  //组装参数
				let para = {
					currentPage: this.currentPage,
          pageSize: this.pageSize,
          //高级查询的参数
          keyword: this.keyword
				};
				//显示加载框
				this.listLoading = true;
				//NProgress.start();

        this.$http.post("/pet",para).then(res =>{
          this.totals = res.data.totals;
          this.pets = res.data.data;
          this.listLoading = false
        }).catch(res =>{
          this.$message.error("网络繁忙，请稍后重试!!!")
            })
			},
			//6.显示编辑界面的对话框
			handleSave: function (index, row) {
        this.title = "编辑";
				this.saveFormVisible = true;
				this.saveForm = Object.assign({}, row);
        this.getUsers();
        this.getShops();
        this.getPetTypeTree();
        this.fileList=[];//将fileList清空 否则编辑和添加对话框中的图片会起冲突
        //点击修改将resources中的数据 - 装到fileList中
        if(this.saveForm.resources) {//处理resources,由于其无法做v-model双向绑定，故放到filelist中重新添加
          let arr = this.saveForm.resources.split(",");//[xx,xx,xx]
          for (var i = 0; i < arr.length; i++) {
            this.fileList.push({"url": "http://123.207.27.208" + arr[i]});
          }
        }
			},

			//7.显示新增界面的对话框
			handleAdd: function () {
        this.title = "添加";
				this.saveFormVisible = true;
				this.saveForm = {
          id: null,
          username: '',
          phone: '',
          email: '',
          password: '',
          age: null,
          state: 1,
          parentId: null,
          petDetail:{
            intro: '',
            adoptNotice: '',
          }
				};
        this.fileList=[];
        this.getUsers();
        this.getShops();
       this.getPetTypeTree();
			},
			//8.点击提交数据
			saveSubmit: function () {
        //将所有ref的表单【ref="saveForm"】,validate-验证
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
              //显示提交的加载框
							this.saveLoading = true;

							//解决上级菜单 下拉框选择出现的问题，【parentId 为对话框中的typeId 为级联框中的数据】
							let para = Object.assign({}, this.saveForm);
							if(para.typeId==null || para.typeId.length==0){
							  para.typeId=null;
              }else if(para.typeId.length){
                para.typeId=para.typeId[para.typeId.length-1]
              }

              //发送请求
							this.$http.put("/pet",para).then((res) => {
                //关闭提交的加载框
								this.saveLoading = false;
                //关闭对话框
                this.saveFormVisible = false;

                if(res.data.success){
                  this.$message.success("操作成功");
                  this.getPets();
                }else{
                  this.$message.error("系统异常，请稍后重试!【500】");
                }
							}).catch((res)=>{
                this.$message.error("系统异常，请稍后重试!【服务器没开,404,400,405】")
              })
						});
					}
				});
			},
      //10.获取宠物树
      getPetTypeTree(){
        this.$http.get("/petType/petTypeTree").then(res=>{
          this.petTypeTree = res.data;
        })
      },
      //图片上传成功之后的回调
      handleSuccess(response, file, fileList){//response 相当于 ajaxresult
        //1.只要把action属性写对了就可以上传了
        //处理resources
        if(this.saveForm.resources){//有值
          this.saveForm.resources = this.saveForm.resources+","+response.obj;
        }else{
          this.saveForm.resources = response.obj;
        }

        //处理fileList:resources = xx,xx,xx
        this.fileList=[];//先清空 - 再添加最新的所有该宠物图片
        if(this.saveForm.resources){
          let arr = this.saveForm.resources.split(",");//[xx,xx,xx]
          for(var i = 0;i<arr.length;i++){
            this.fileList.push({"url":"http://123.207.27.208"+arr[i]});
          }
        }
      },
      //文件删除的业务逻辑
      handleRemove(file, fileList){
      //1.调用删除接口删除fastdfs中的数据 :
        var url = file.url;//http://123.207.27.208/group1/M00/00/0C/CgAIC2KrU4qAAy6HAAF5fdD2FCI828.jpg
        var path = url.substring(url.indexOf("/group"));// /group1/M00/00/0C/CgAIC2KrU4qAAy6HAAF5fdD2FCI828.jpg
        this.$http.delete("/fastDfs?path="+path).then(res=>{
          if(res.data.success){
            this.$message.success("删除成功!!!");
          }else{
            this.$message.success("删除失败!!!");
          }
        })

        //2.处理resources
        if(this.saveForm.resources){ // xx,yy,zz
          let arr = this.saveForm.resources.split(","); //[xx,yy,zz]
          for(var i = 0;i<arr.length;i++){
            if(path == arr[i]){//找到了删除的图片
              arr.splice(i,1);
              break;
            }
          }         //[xx,zz]
          this.saveForm.resources = arr.join(","); //xx,zz
        }

        //3.处理fileList
        this.fileList=[];//先清空 - 再添加最新的所有该宠物图片
        if(this.saveForm.resources){
          let arr = this.saveForm.resources.split(",");//[xx,xx,xx]
          for(var i = 0;i<arr.length;i++){
            this.fileList.push({"url":"http://123.207.27.208"+arr[i]});
          }
        }
      },
      offsale(){
        var ids = this.sels.map(item => item.id);
        //获取选中的行
        if(!this.sels || this.sels.length  <1){
          this.$message({ message: '老铁，你不选中数据，下架不了啊....',type: 'error'});
          return;
        }
        this.$confirm('确认下架选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.post('/pet/offsale',ids).then((res) => {
            this.listLoading = false;

            if(res.data.success){
              this.$message({
                message: '下架成功',
                type: 'success'
              });
            }else{
              this.$message({
                message: res.data.message,
                type: 'error'
              });
            }
            this.getPets();//刷新页面
          }).catch(res => {
            this.$message({
              message: "系统错误，请稍后重试!!!",
              type: 'error'
            });
          })
        });
      },
      onsale(){
        //seles 是选中的对象 赋值给数组，map方法把每个item对象的id获取出来形成一个新数组
        var ids = this.sels.map(item => item.id);
        //获取选中的行
        if(!this.sels || this.sels.length  <1){
          this.$message({ message: '老铁，你不选中数据，上架不了啊....',type: 'error'});
          return;
        }

        this.$confirm('确认上架选中的数据吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.post('/pet/onsale',ids).then((res) => {
            this.listLoading = false;
            if(res.data.success){
              this.$message({
                message: '上架成功',
                type: 'success'
              });
            }else{
              this.$message({
                message: res.data.message,
                type: 'error'
              });
            }
            this.getPets();// 刷新页面
          }).catch(res => {
            this.$message({
              message: "系统错误，请稍后重试!!!",
              type: 'error'
            });
          })
        });
      },
		},
		mounted() {
			this.getPets();
		}
	}

</script>

<style scoped>

</style>